package com.wannengbang.cloudleader.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AgentListBean;
import com.wannengbang.cloudleader.bean.StoreListBean;
import com.wannengbang.cloudleader.homepage.adapter.ChooseAgentListAdapter;
import com.wannengbang.cloudleader.homepage.adapter.ChooseStoreListAdapter;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.utils.DisplayUtil;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 选择合伙人
 */
public class ChooseAgentDialog extends DialogFragment {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.recyclerView_agent)
    RecyclerView recyclerViewAgent;
    @BindView(R.id.recyclerView_store)
    RecyclerView recyclerViewStore;
    private Dialog dialog;
    private OnCallBackListener onCallBackListener;
    private Activity mActivity;
    private String type;
    private String giveType;
    private List<AgentListBean.DataBean.ItemListBean> allAgentList = new ArrayList<>();
    private List<AgentListBean.DataBean.ItemListBean> agentList = new ArrayList<>();
    private List<StoreListBean.DataBean.ItemListBean> allStoreList = new ArrayList<>();
    private List<StoreListBean.DataBean.ItemListBean> storeList = new ArrayList<>();
    private ChooseAgentListAdapter agentListAdapter;
    private ChooseStoreListAdapter storeListAdapter;
    private String keyword = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_choose_agent, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();
        initView();
        return view;
    }

    public static ChooseAgentDialog newInstance(String type, String giveType) {
        Bundle args = new Bundle();
        ChooseAgentDialog fragment = new ChooseAgentDialog();
        args.putString("type", type);
        args.putString("giveType", giveType);
        fragment.setArguments(args);
        return fragment;
    }

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    //    初始化请求
    private void initView() {
        type = getArguments().getString("type");
        giveType = getArguments().getString("giveType");

        if (giveType.equals("1")) {
            tvTitle.setText("选择合伙人");
            recyclerViewAgent.setVisibility(View.VISIBLE);
            recyclerViewStore.setVisibility(View.GONE);
            agentListAdapter = new ChooseAgentListAdapter(agentList);
            recyclerViewAgent.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
            recyclerViewAgent.setAdapter(agentListAdapter);
            agentListAdapter.setOnCallBackListener((name, chooseId) -> {
                dismiss();
                onCallBackListener.onCallBack(name, chooseId);
            });
            requestTransferAgentIndex();
        } else {
            tvTitle.setText("选择门店");
            recyclerViewAgent.setVisibility(View.GONE);
            recyclerViewStore.setVisibility(View.VISIBLE);
            storeListAdapter = new ChooseStoreListAdapter(storeList);
            recyclerViewStore.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
            recyclerViewStore.setAdapter(storeListAdapter);
            storeListAdapter.setOnCallBackListener((name, chooseId) -> {
                dismiss();
                onCallBackListener.onCallBack(name, chooseId);
            });

            requestStoreIndex();
        }

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(keyword)) {

                        if (giveType.equals("1")) {
                            agentList.clear();
                            for (AgentListBean.DataBean.ItemListBean listBean : allAgentList) {
                                String content = listBean.getName() + "(" + listBean.getMobile() + ")";
                                if (content.contains(keyword) || content.equals(keyword)) {
                                    agentList.add(listBean);
                                }
                            }
                            agentListAdapter.notifyDataSetChanged();
                        } else {
                            storeList.clear();
                            for (StoreListBean.DataBean.ItemListBean listBean : allStoreList) {
                                String content = listBean.getName() + "(" + listBean.getContact_mobile() + ")";
                                if (content.contains(keyword) || content.equals(keyword)) {
                                    storeList.add(listBean);
                                }
                            }
                            storeListAdapter.notifyDataSetChanged();
                        }

                    }
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = editSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                    if (giveType.equals("1")) {
                        agentList.clear();
                        agentList.addAll(allAgentList);
                        agentListAdapter.notifyDataSetChanged();
                    } else {
                        storeList.clear();
                        storeList.addAll(allStoreList);
                        storeListAdapter.notifyDataSetChanged();
                    }
                }

                if (!TextUtils.isEmpty(keyword)) {
                    if (giveType.equals("1")) {
                        agentList.clear();
                        for (AgentListBean.DataBean.ItemListBean listBean : allAgentList) {
                            String content = listBean.getName() + "(" + listBean.getMobile() + ")";
                            if (content.contains(keyword) || content.equals(keyword)) {
                                agentList.add(listBean);
                            }
                        }
                        agentListAdapter.notifyDataSetChanged();
                    } else {
                        storeList.clear();
                        for (StoreListBean.DataBean.ItemListBean listBean : allStoreList) {
                            String content = listBean.getName() + "(" + listBean.getContact_mobile() + ")";
                            if (content.contains(keyword) || content.equals(keyword)) {
                                storeList.add(listBean);
                            }
                        }
                        storeListAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = (int) (DisplayUtil.getScreenHeight() * 0.7);
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    public void requestTransferAgentIndex() {
        new HomePageModelImpl().requestTransferAgentIndex(new DataCallBack<AgentListBean>() {
            @Override
            public void onSuccessful(AgentListBean bean) {
                allAgentList.addAll(bean.getData().getItemList());
                agentList.addAll(allAgentList);
                agentListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    public void requestStoreIndex() {
        new HomePageModelImpl().requestStoreIndex(new DataCallBack<StoreListBean>() {
            @Override
            public void onSuccessful(StoreListBean bean) {
                allStoreList.addAll(bean.getData().getItemList());
                storeList.addAll(allStoreList);
                storeListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.view_cancel, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_cancel:
                editSearch.setText("");
                keyword = "";

                if (giveType.equals("1")) {
                    agentList.clear();
                    agentList.addAll(allAgentList);
                    agentListAdapter.notifyDataSetChanged();
                } else {
                    storeList.clear();
                    storeList.addAll(allStoreList);
                    storeListAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(keyword)) {
                    ToastUtil.showShort("请输入搜索内容");
                    return;
                }
                if (giveType.equals("1")) {
                    agentList.clear();
                    for (AgentListBean.DataBean.ItemListBean listBean : allAgentList) {
                        String content = listBean.getName() + "(" + listBean.getMobile() + ")";
                        if (content.contains(keyword) || content.equals(keyword)) {
                            agentList.add(listBean);
                        }
                    }
                    agentListAdapter.notifyDataSetChanged();
                } else {
                    storeList.clear();
                    for (StoreListBean.DataBean.ItemListBean listBean : allStoreList) {
                        String content = listBean.getName() + "(" + listBean.getContact_mobile() + ")";
                        if (content.contains(keyword) || content.equals(keyword)) {
                            storeList.add(listBean);
                        }
                    }
                    storeListAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    public interface OnCallBackListener {
        void onCallBack(String name, String chooseId);
    }
}
